package com.leyou.item.controller;

import com.leyou.item.entity.Spu;
import com.leyou.item.entity.SpuDetail;
import com.leyou.item.service.SpuDetailService;
import com.leyou.item.service.SpuService;
import com.leyou.item.vo.PageResult;
import com.leyou.item.vo.SpuVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * http://api.leyou.com/api/item/spu/page?key=&saleable=true&page=1&rows=5
 * http://api.leyou.com/api/item/spu/detail/195
 *
 * @author linzx
 * @date 2020/3/25
 */
@RestController
@RequestMapping("spu")
public class SpuController {
    @Autowired
    private SpuService spuService;
    @Autowired
    private SpuDetailService spuDetailService;

    /**
     * 分页查询skuvo
     *
     * @param key
     * @param saleable
     * @param page
     * @param rows
     * @return
     */
    @GetMapping("page")
    public ResponseEntity<PageResult<SpuVO>> querySpuPage(
            @RequestParam(value = "key", required = false) String key,
            @RequestParam(value = "saleable", required = false) Boolean saleable,
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "rows", defaultValue = "5") Integer rows
    ) {
        return ResponseEntity.ok(spuService.querySpuPage(key, saleable, page, rows));
    }

    /**
     * 根据id查询SpuDetail
     *
     * @param spuId
     * @return
     */
    @GetMapping("detail/{spuId}")
    public ResponseEntity<SpuDetail> findSpuDetailById(@PathVariable("spuId") Long spuId) {
        return ResponseEntity.ok(spuDetailService.selectByPrimaryKey(spuId));
    }

    @PutMapping("saleable")
    public ResponseEntity<Void> updateSaleable(
            @RequestParam("saleable") Boolean saleable,
            @RequestParam("spuid") Long spuId
    ) {
        Spu spu = new Spu();
        spu.setLastUpdateTime(new Date());
        spu.setId(spuId);
        spu.setSaleable(saleable);
        spuService.updateByPrimaryKeySelective(spu);
        return ResponseEntity.ok().build();
    }

    /**
     * 根据id查询spu
     * @param id
     * @return
     */
    @GetMapping("{id}")
    public ResponseEntity<Spu> querySpuById(@PathVariable("id")Long id) {
        return ResponseEntity.ok(spuService.selectByPrimaryKey(id));
    }

    /**
     * 根据ids查询spu
     * @param ids
     * @return
     */
    @GetMapping("list")
    public ResponseEntity<List<Spu>> querySpuById(@RequestParam("ids")List<Long> ids) {
        return ResponseEntity.ok(spuService.selectByIdList(ids));
    }
}
